package com.ruoyi.picture.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.picture.domain.FamParm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.picture.mapper.FamsMapper;
import com.ruoyi.picture.domain.Fam;
import com.ruoyi.picture.service.IFamService;

/**
 * 家人账单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-16
 */
@Service
public class FamServiceImpl implements IFamService {
    @Autowired
    private FamsMapper famsMapper;

    /**
     * 查询家人账单
     *
     * @param id 家人账单主键
     * @return 家人账单
     */
    @Override
    public Fam selectFamById(Long id) {

        return famsMapper.selectFamById(id);
    }

    /**
     * 查询家人账单列表
     *
     * @param fam 家人账单
     * @return 家人账单
     */
    @Override
    public List<Fam> selectFamList(Fam fam) {
        String names = "";
        List<Fam> fams = famsMapper.famsList();
        List<String> famList;
        for (Fam f : fams) {
            famList = famsMapper.selectFamList(f).stream().map(item -> item.getNickName()).collect(Collectors.toList());
            names = "";
            for (String s : famList) {
                names += s + ';';
            }
            if (!famList.isEmpty()) {
                f.setNames(names);
            }

        }

        return fams;
    }

    /**
     * 新增家人账单
     *
     * @param fam 家人账单
     * @return 结果
     */
    @Override
    public int insertFam(Fam fam) {
        List<Fam> fams = famsMapper.selectFamList(fam);
        if (!fams.isEmpty()) {
            return 5;
        }
        return famsMapper.insertFam(fam);
    }

    /**
     * 修改家人账单
     *
     * @param fam 家人账单
     * @return 结果
     */
    @Override
    public int updateFam(Fam fam) {
        return famsMapper.updateFam(fam);
    }

    /**
     * 批量删除家人账单
     *
     * @param ids 需要删除的家人账单主键
     * @return 结果
     */
    @Override
    public int deleteFamByIds(Long[] ids) {
        return famsMapper.deleteFamByIds(ids);
    }

    /**
     * 删除家人账单信息
     *
     * @param id 家人账单主键
     * @return 结果
     */
    @Override
    public int deleteFamById(Long id) {
        return famsMapper.deleteFamById(id);
    }

    @Override
    public int insertFams(FamParm famParm) {
        List<Long> ids = famParm.getIds();
        famsMapper.deleteFamById(famParm.getFid());
        if (ids.isEmpty()){
            Fam fam1 = new Fam();
            fam1.setId(null);
            fam1.setFamId(famParm.getFid());
        }

        for (Long id : ids) {
            Fam fam = famsMapper.selectByuserId(id);
            if (fam!=null){
                return 0;
            }
            Fam fam1 = new Fam();
            fam1.setId(null);
            fam1.setFamId(famParm.getFid());
            fam1.setUserId(id);
            int i = famsMapper.insertFam(fam1);
        }
        return 1;
    }
}
